package com.bw.image

import android.content.Context
import android.os.Environment
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.internal.cache.InternalCache
import java.io.File
import java.io.InputStream


/**
 * 自定义Glide内存和磁盘缓存大小
 */
@com.bumptech.glide.annotation.GlideModule
class GlideModule : AppGlideModule() {

    override fun applyOptions(context: Context, builder: GlideBuilder) {
        //1.修改内存缓存大小 默认是1/8
        val memorySize = MemorySizeCalculator.Builder(context).build()
            .memoryCacheSize / 6L
        builder.setMemoryCache(LruResourceCache(memorySize))

        //2.修改磁盘缓存大小 默认250MB
        builder.setDiskCache(
            InternalCacheDiskCacheFactory(
                context,
                "glide_disk_cache",
                300 * 1024 * 1024
            )
        )


    }

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        //3.网络缓存大小

        //创建builder
        val builder = OkHttpClient.Builder()

        //外部sd卡缓存目录
        val externalDir = Environment.getExternalStorageDirectory()


        val cacheDir = if (externalDir.exists()) {
            "${externalDir.absolutePath}/cacheImage"
        } else {
            //没有就用内部的
            "${context.externalCacheDir?.absolutePath}/internal_cache_image"
        }


        var cacheDirFile = File(cacheDir)
        if (!cacheDirFile.exists()) {
            //设置缓存目录
            cacheDirFile = File(cacheDir)
        }


        //计算缓存大小
        var cacheSize = 50 * 1024 * 1024L
        externalDir.totalSpace?.let {
            cacheSize = it / 8L
        }
        val netWorkCache = Cache(cacheDirFile, cacheSize)


        builder.cache(netWorkCache)
        val client = builder.build()

        //替换网络缓存客户端
        registry.replace(
            GlideUrl::class.java,
            InputStream::class.java,
            OkHttpUrlLoader.Factory(client)
        )


    }


}